<?php

namespace app\common\controller;
use app\common\controller\Common;
use think\Controller;
use think\facade\Request;
use think\Validate;

/**
 * 接口控制器，如果需要跨域、加密等可以继承这个类
 * @package app\index\controller
 */
class Api extends Common {
	public $decryptData = [];
	protected function __construct() {
		//跨域设置
		$url = "http://www.test.com";
		// //制定允许其他域名访问
		// header('Access-Control-Allow-Origin:' . $url);
		// // 响应类型
		// header('Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE');
		// //请求头
		// header('Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language,Origin,Accept-Encoding,Token,Encrypt,encrypt');
		// // 响应头设置
		// header('Access-Control-Allow-Credentials:true');
		$header = Request::header();
		$param = $this->request->param();

		//加密数据请在header中加入encrypt=1
		if (isset($header['encrypt']) && isset($param['data'])) {

			$this->decryptData = aes_decrypt($param['data'], config("api.aes_key"), config("api.aes_iv"));
			$data = [];
			if (gettype($this->decryptData) == 'string') {
				$this->decryptData = [];
			}
			if (stripos($header['content-type'], "x-www-form-urlencoded") !== false && !empty($this->decryptData) && count($this->decryptData) > 0) {
				foreach ($this->decryptData as $v) {

					if (isset($v['name']) && isset($v['value'])) {
						$data[$v['name']] = $v['value'];
					}
				}
				$this->decryptData = array_merge($data, $this->decryptData);
			}
			if (empty($this->decryptData)) {
				$this->decryptData = $param;
			}
		} else {
			$this->decryptData = $param;
		}

	}
	/**
	 *  校验参数
	 * @author MrGuo <gj2518@qq.com>
	$msg=$this->validate([
	['mobile'=>'require|length:7,15'],
	]);
	 */
	public function validateParam($rules = [], $isPost = true) {
		$header = Request::header();
		$param = Request::param();
		if (isset($header['encrypt']) && isset($param['data'])) {
			$param = $this->decryptData;
		} else {
			if (!$isPost) {
				$param = $this->request->param();
			} else {
				$param = $this->request->post();
			}
		}

		foreach ($rules as $key => $val) {
			$validate = new Validate($val);
			if (!$validate->check($param)) {
				return ($validate->getError());
			}
		}
		return true;
	}
	public function checkLogin() {
		$uid = intval(session("user_web.id"));
		if ($uid < 1) {
			$arr = [
				'code' => 601, "msg" => "登录已失效，请重新登录",
			];
			header("Content-Type:application/json");
			echo json_encode($arr, JSON_UNESCAPED_UNICODE);
			exit;
		}
	}
}
